// api/index.ts - 简化的API模块入口
import { authManager } from './auth-manager';

/** 简化的HTTP客户端 */
class SimpleHttpClient {
  private baseUrl: string;
  
  constructor() {
    // 根据环境自动设置baseUrl
    this.baseUrl = this.getBaseUrl();
  }
  
  private getBaseUrl(): string {
    // 微信小程序环境检测
    try {
      const wxConfig = (wx as any).__wxConfig || (getApp() as any).__wxConfig;
      if (wxConfig) {
        const envVersion = wxConfig.envVersion;
        switch (envVersion) {
          case 'release':
            return 'https://xhd.szxhdkj.com';
          case 'trial':
            return 'https://xhd.szxhdkj.com';
          case 'develop':
          default:
            return 'https://xhd.szxhdkj.com';
            // return 'http://192.168.137.1:8090';
        }
      }
    } catch (error) {
      console.log('获取微信配置失败，使用默认URL');
    }
    // return 'http://192.168.137.1:8090';
    return 'https://xhd.szxhdkj.com';
  }

  /** 文件上传方法 */
  async uploadFile(config: {
    url: string;
    filePath?: string;
    fileData?: string; // Base64数据
    fileName: string;
    formData?: Record<string, any>;
    skipAuth?: boolean;
    showLoading?: boolean;
    loadingText?: string;
  }): Promise<any> {
    const {
      url,
      filePath,
      fileData,
      fileName,
      formData = {},
      skipAuth = false,
      showLoading = false,
      loadingText = '上传中...'
    } = config;

    // 生成请求ID用于日志追踪
    const requestId = Math.random().toString(36).substr(2, 9);
    const startTime = Date.now();

    // 显示loading
    if (showLoading) {
      wx.showLoading({ title: loadingText });
    }

    try {
      // 构建完整URL
      const fullUrl = url.startsWith('http') ? url : `${this.baseUrl}${url}`;
      
      // 构建请求头
      const headers: Record<string, string> = {};
      
      // 添加Token
      if (!skipAuth && authManager.isAuthenticated()) {
        const token = authManager.getToken();
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
      }

      console.log(`[UPLOAD-${requestId}] 🚀 开始文件上传:`, {
        url: fullUrl,
        fileName,
        hasFilePath: !!filePath,
        hasFileData: !!fileData,
        formDataKeys: Object.keys(formData),
        timestamp: new Date().toISOString()
      });

      let response: any;

      if (fileData) {
        // 使用Base64数据上传
        const uploadData = {
          ...formData,
          fileName,
          fileData,
          timestamp: Date.now()
        };

        response = await new Promise<any>((resolve, reject) => {
          wx.request({
            url: fullUrl,
            method: 'POST',
            data: uploadData,
            header: {
              ...headers,
              'Content-Type': 'application/json'
            },
            timeout: 30000, // 文件上传使用更长的超时时间
            success: resolve,
            fail: reject
          });
        });
      } else if (filePath) {
        // 使用微信原生文件上传
        response = await new Promise<any>((resolve, reject) => {
          wx.uploadFile({
            url: fullUrl,
            filePath,
            name: 'file',
            formData: {
              ...formData,
              fileName
            },
            header: headers,
            timeout: 30000,
            success: resolve,
            fail: reject
          });
        });
      } else {
        throw new Error('必须提供 filePath 或 fileData');
      }

      const duration = Date.now() - startTime;

      console.log(`[UPLOAD-${requestId}] ✅ 上传成功:`, {
        statusCode: response.statusCode,
        duration: `${duration}ms`,
        timestamp: new Date().toISOString()
      });

      // 更新活跃时间
      if (!skipAuth) {
        authManager.updateLastActiveTime();
      }

      // 处理响应
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // 如果响应是字符串，尝试解析为JSON
        if (typeof response.data === 'string') {
          try {
            response.data = JSON.parse(response.data);
          } catch (parseError) {
            console.warn(`[UPLOAD-${requestId}] ⚠️ 响应数据不是有效JSON`);
          }
        }
        
        return response;
      } else {
        throw new Error(`上传失败: ${response.statusCode}`);
      }
      
    } catch (error: any) {
      const duration = Date.now() - startTime;
      
      console.error(`[UPLOAD-${requestId}] ❌ 上传失败:`, {
        error: error.message || error,
        duration: `${duration}ms`,
        timestamp: new Date().toISOString()
      });
      
      throw error;
    } finally {
      if (showLoading) {
        wx.hideLoading();
      }
    }
  }

  /** 通用请求方法 */
  private async request(config: {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    skipAuth?: boolean;
    showLoading?: boolean;
    loadingText?: string;
  }): Promise<any> {
    const {
      url,
      method = 'GET',
      data,
      skipAuth = false,
      showLoading = false,
      loadingText = '加载中...'
    } = config;

    // 生成请求ID用于日志追踪
    const requestId = Math.random().toString(36).substr(2, 9);
    const startTime = Date.now();

    // 显示loading
    if (showLoading) {
      wx.showLoading({ title: loadingText });
    }

    try {
      // 构建完整URL
      const fullUrl = url.startsWith('http') ? url : `${this.baseUrl}${url}`;
      
      // 构建请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };
      
      // 添加Token
      if (!skipAuth && authManager.isAuthenticated()) {
        const token = authManager.getToken();
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
      }

      // 记录请求开始日志
      console.log(`[HTTP-${requestId}] 🚀 发起请求:`, {
        url: fullUrl,
        method,
        headers: this.sanitizeHeaders(headers),
        data: this.sanitizeData(data),
        timestamp: new Date().toISOString()
      });

      // 发起请求
      const response = await new Promise<any>((resolve, reject) => {
        wx.request({
          url: fullUrl,
          method: method as any,
          data,
          header: headers,
          timeout: 15000,
          success: resolve,
          fail: reject
        });
      });

      const duration = Date.now() - startTime;

      // 记录响应成功日志
      console.log(`[HTTP-${requestId}] ✅ 请求成功:`, {
        statusCode: response.statusCode,
        duration: `${duration}ms`,
        responseData: this.sanitizeResponseData(response.data),
        timestamp: new Date().toISOString()
      });

      // 更新活跃时间
      if (!skipAuth) {
        authManager.updateLastActiveTime();
      }

      // 检查是否有刷新的Token
      if (!skipAuth && response.header && response.header['X-Refreshed-Token']) {
        try {
          const refreshedToken = response.header['X-Refreshed-Token'];
          if (refreshedToken && refreshedToken.startsWith('Bearer ')) {
            const newToken = refreshedToken.substring(7); // 移除 'Bearer ' 前缀
            console.log(`[HTTP-${requestId}] 🔄 检测到服务器刷新的Token，更新本地存储`);
            
            // 更新认证管理器中的Token
            await authManager.updateToken(newToken);
          }
        } catch (error) {
          console.warn(`[HTTP-${requestId}] ⚠️ 处理刷新Token失败:`, error);
        }
      }

      // 处理响应
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // 处理空响应或非JSON响应
        if (!response.data || response.data === '' || response.data === null) {
          console.warn(`[HTTP-${requestId}] ⚠️ 服务器返回空响应，使用默认数据结构`);
          response.data = { code: 0, message: '成功', data: null };
        }
        
        // 如果响应是字符串，尝试解析为JSON
        if (typeof response.data === 'string') {
          try {
            response.data = JSON.parse(response.data);
          } catch (parseError) {
            console.warn(`[HTTP-${requestId}] ⚠️ 响应数据不是有效JSON，原始数据:`, response.data);
            // 如果解析失败，包装成标准格式
            response.data = { 
              code: 0, 
              message: '成功', 
              data: response.data || null 
            };
          }
        }
        
        return response;
      } else {
        throw new Error(`请求失败: ${response.statusCode}`);
      }
      
    } catch (error: any) {
      const duration = Date.now() - startTime;
      
      // 记录请求失败日志
      console.error(`[HTTP-${requestId}] ❌ 请求失败:`, {
        error: error.message || error,
        statusCode: error.statusCode,
        duration: `${duration}ms`,
        timestamp: new Date().toISOString()
      });
      
      // 处理401错误
      if (error.statusCode === 401 && !skipAuth) {
        console.log(`[HTTP-${requestId}] 🔒 检测到401错误，执行自动登出`);
        await authManager.logout();
        wx.showModal({
          title: '登录过期',
          content: '请重新登录',
          showCancel: false,
          success: () => {
            wx.navigateTo({ url: '/pages/login/login' });
          }
        });
      }
      
      throw error;
    } finally {
      if (showLoading) {
        wx.hideLoading();
      }
    }
  }

  /** 清理请求头敏感信息用于日志 */
  private sanitizeHeaders(headers: Record<string, string>): Record<string, string> {
    const sanitized = { ...headers };
    if (sanitized['Authorization']) {
      sanitized['Authorization'] = 'Bearer ****';
    }
    return sanitized;
  }

  /** 清理请求数据敏感信息用于日志 */
  private sanitizeData(data: any): any {
    if (!data) return data;
    
    const sensitiveFields = ['password', 'token', 'encryptedData', 'iv'];
    const sanitized = JSON.parse(JSON.stringify(data));
    
    const sanitizeObject = (obj: any): void => {
      if (typeof obj === 'object' && obj !== null) {
        for (const key in obj) {
          if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
            obj[key] = '****';
          } else if (typeof obj[key] === 'object') {
            sanitizeObject(obj[key]);
          }
        }
      }
    };
    
    sanitizeObject(sanitized);
    return sanitized;
  }

  /** 清理响应数据敏感信息用于日志 */
  private sanitizeResponseData(data: any): any {
    if (!data) return data;
    
    try {
      const sensitiveFields = ['token', 'password', 'encryptedData'];
      const sanitized = JSON.parse(JSON.stringify(data));
      
      const sanitizeObject = (obj: any): void => {
        if (typeof obj === 'object' && obj !== null) {
          for (const key in obj) {
            if (sensitiveFields.some(field => key.toLowerCase().includes(field))) {
              obj[key] = '****';
            } else if (typeof obj[key] === 'object') {
              sanitizeObject(obj[key]);
            }
          }
        }
      };
      
      sanitizeObject(sanitized);
      return sanitized;
    } catch {
      return '[无法解析响应数据]';
    }
  }

  /** GET请求 */
  async get(url: string, params?: any, options?: any): Promise<any> {
    let requestUrl = url;
    if (params) {
      const query = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');
      requestUrl += `?${query}`;
    }
    
    return this.request({ url: requestUrl, method: 'GET', ...options });
  }

  /** POST请求 */
  async post(url: string, data?: any, options?: any): Promise<any> {
    return this.request({ url, method: 'POST', data, ...options });
  }

  /** PUT请求 */
  async put(url: string, data?: any, options?: any): Promise<any> {
    return this.request({ url, method: 'PUT', data, ...options });
  }

  /** DELETE请求 */
  async delete(url: string, data?: any, options?: any): Promise<any> {
    return this.request({ url, method: 'DELETE', data, ...options });
  }
}

// 创建HTTP客户端实例
const http = new SimpleHttpClient();

/** 简化的API对象 */
const api = {
  // HTTP方法
  get: http.get.bind(http),
  post: http.post.bind(http),
  put: http.put.bind(http),
  delete: http.delete.bind(http),

  // 文件上传方法
  uploadFile: (config: {
    url: string;
    filePath?: string;
    fileData?: string;
    fileName: string;
    formData?: Record<string, any>;
    skipAuth?: boolean;
    showLoading?: boolean;
    loadingText?: string;
  }) => http.uploadFile(config),

  // 上传表盘背景图片
  uploadDialBackground: (data: {
    userId: number;
    fileName: string;
    fileData: string;
    fileSize: number;
    fileType: string;
    format: string;
    originalFileName?: string;
  }) => {
    console.log('🎨 [uploadDialBackground] 上传表盘背景图片');
    return http.uploadFile({
      url: '/api/dial/background/upload',
      fileData: data.fileData,
      fileName: data.fileName,
      formData: {
        userId: data.userId,
        fileSize: data.fileSize,
        fileType: data.fileType,
        format: data.format,
        originalFileName: data.originalFileName || data.fileName
      },
      showLoading: true,
      loadingText: '上传表盘背景中...'
    });
  },

  // 获取设备表盘背景URL
  getDeviceDialBackground: (deviceId: string) => {
    console.log('🎨 [getDeviceDialBackground] 获取设备表盘背景URL:', deviceId);
    return http.get(`/api/device/${deviceId}/dial-background`);
  },

  // 认证相关
  login: (data: { username: string; password: string }) => 
    http.post('/api/user/login', data, { skipAuth: true, showLoading: true, loadingText: '登录中...' }),
  
  wechatPhoneLogin: (data: { 
    code: string; 
    encryptedData: string; 
    iv: string; 
    create_if_not_exists?: boolean;
    fromOfficialAccount?: boolean;
    officialAccountOpenid?: string;
    unionid?: string;
    launchScene?: string | number;
    needUnionId?: boolean;
  }) =>
    http.post('/api/wechat/login/phone', data, { skipAuth: true, showLoading: true, loadingText: '微信登录中...' }),

  logout: () => 
    http.post('/api/user/logout', {}, { showLoading: true, loadingText: '退出中...' }),

  // 用户相关
  getUserInfo: () => 
    http.get('/api/user/profile'),
  
  updateUserInfo: (data: any) => 
    http.put('/api/user/profile', data, { showLoading: true, loadingText: '更新中...' }),
  
  // 更新用户资料（包括 unionid）
  updateUserProfile: (data: any) => {
    console.log('[API] 🔄 更新用户资料:', JSON.stringify(data));
    return http.put('/api/user/profile', data, { 
      showLoading: false,
      headers: {
        'X-Update-Profile': 'true'  // 添加特殊标记，让后端知道这是更新用户资料的请求
      }
    });
  },
    
  updateDailyTarget: async (dailyGoal: number, userId?: number) => {
    // 如果没有传入userId，先获取当前用户信息
    if (!userId) {
      try {
        const userProfile = await http.get('/api/user/profile');
        if (userProfile?.data?.data?.id) {
          userId = userProfile.data.data.id;
        } else {
          throw new Error('无法获取用户ID');
        }
      } catch (error) {
        console.error('获取用户ID失败:', error);
        // 使用缓存的用户ID作为备用
        try {
          const cachedUserId = wx.getStorageSync('userId');
          if (cachedUserId) {
            userId = cachedUserId;
          } else {
            throw new Error('无法获取用户ID');
          }
        } catch (storageError) {
          console.error('读取本地存储失败:', storageError);
          throw new Error('无法获取用户ID');
        }
      }
    }
    
    const url = `/api/user/${userId}/daily-goal?dailyGoal=${dailyGoal}`;
    return http.put(url, {}, { showLoading: true, loadingText: '更新目标中...' });
  },

  // 设备相关
  getDeviceList: (params?: any) => 
    http.get('/api/device/list', params),
  
  getDeviceByUserId: (userId: number) => 
    http.get(`/api/device/user/${userId}`),
  
  getDeviceStatus: (deviceSn: string) => 
    http.get(`/api/device/${deviceSn}/status`),

  // 记录相关
  getWaterRecordList: (params?: any) => 
    http.get('/api/record/list', params),
  
  addRecord: (data: { amount: number; type?: string; timestamp?: number }) => 
    http.post('/api/water-record', { ...data, timestamp: data.timestamp || Date.now() }, 
      { showLoading: true, loadingText: '添加记录中...' }),
  
  getStatistics: (params?: any) => 
    http.get('/api/water-record/statistics', params),

  // 系统相关
  getSystemConfig: () => 
    http.get('/api/system/config', null, { skipAuth: true }),
  
  submitFeedback: (data: any) => 
    http.post('/api/system/feedback', data, { showLoading: true, loadingText: '提交反馈中...' }),

  // ==================== 设备管理接口 ====================
  
  // 获取用户设备列表
  getDevices: async () => {
    try {
      // 首先获取当前用户信息
      const userProfile = await http.get('/api/user/profile');
      if (userProfile?.data?.data?.id) {
        const userId = userProfile.data.data.id;
        console.log('🔍 获取用户设备列表，用户ID:', userId);
        return http.get(`/api/device/user/${userId}`);
      } else {
        console.warn('⚠️ 无法获取用户ID，返回空设备列表');
        return { data: { code: 0, message: '成功', data: [] } };
      }
    } catch (error) {
      console.error('❌ 获取用户设备列表失败:', error);
      // 返回默认空数据结构
      return { data: { code: 0, message: '成功', data: [] } };
    }
  },
  
  // 获取设备信息 (注意: 当前此接口可能返回400错误)
  getDeviceInfo: (deviceId: string) => 
    http.get(`/api/device/${deviceId}`),
  
  // 更新设备信息
  updateDevice: (deviceId: string, data: { name?: string; settings?: any }) => 
    http.put(`/api/device/${deviceId}/settings`, data, { showLoading: true, loadingText: '更新设备中...' }),
  
  // 删除设备 (完全删除设备记录)
  deleteDevice: (userId: number, deviceSn: string) => 
    http.post(`/api/device/delete?userId=${userId}&deviceSn=${encodeURIComponent(deviceSn)}`, null, { showLoading: true, loadingText: '删除设备中...' }),
  
  // 解绑设备 (只设置user_id为null，保留记录)
  unbindDevice: (userId: number, deviceSn: string) => 
    http.post(`/api/device/unbind?userId=${userId}&deviceSn=${encodeURIComponent(deviceSn)}`, null, { showLoading: true, loadingText: '解绑设备中...' }),
  
  // 绑定设备
  bindDevice: (data: { 
    userId: number; 
    deviceSn: string; 
    deviceId: string; 
    macAddress: string; 
    deviceName: string; 
    model?: string;
    batteryLevel?: number;
    currentVolume?: number;
    waterTemperature?: number;
    deviceTimezone?: string;
    deviceToken?: string;
    edrAddress?: string;
    bleAddress?: string;
  }) => {
    // 将数据转换为URL参数形式
    const params: string[] = [];
    (Object.keys(data) as (keyof typeof data)[]).forEach(key => {
      const value = data[key];
      if (value !== undefined && value !== null) {
        params.push(`${key}=${encodeURIComponent(String(value))}`);
      }
    });
    
    const url = `/api/device/bind?${params.join('&')}`;
    console.log('🔗 绑定设备请求URL:', url);
    console.log('📦 绑定设备参数:', data);
    
    return http.post(url, null, { 
      showLoading: true, 
      loadingText: '绑定设备中...' 
    });
  },

  // 兼容旧版本的方法名
  getRecordList: (params?: any) => api.getWaterRecordList(params),
  getUserDevices: () => api.getDevices(), // 直接调用新的 getDevices 方法
  addDevice: (data: any) => {
    // 兼容旧版本的添加设备方法，转换为绑定设备
    console.log('⚠️ 使用了已弃用的 addDevice 方法，请使用 bindDevice');
    return api.bindDevice(data);
  },

  // ==================== 天气接口 ====================
  
  // 根据城市名获取天气
  getWeatherByCity: (city: string) => 
    http.get(`/api/weather/city/${encodeURIComponent(city)}`, null, { skipAuth: true }),
  
  // 根据经纬度获取天气
  getWeatherByLocation: (latitude: number, longitude: number) => 
    http.get(`/api/weather/location?latitude=${latitude}&longitude=${longitude}`, null, { skipAuth: true }),
  
  // 获取当前天气（默认接口）
  getCurrentWeather: () => 
    http.get('/api/weather/current', null, { skipAuth: true }),

  // 获取天气预报
  getWeatherForecast: (city?: string) => {
    const url = city ? `/api/weather/forecast?city=${encodeURIComponent(city)}` : '/api/weather/forecast';
    return http.get(url, null, { skipAuth: true });
  },

  // ==================== 用户提醒设置接口 ====================
  
  // 获取用户提醒设置
  getReminderSettings: (userId: number) => 
    http.get(`/api/user/reminder/settings/${userId}`),
  
  // 开启/关闭饮水提醒
  toggleReminder: (userId: number, enabled: boolean) => 
    http.post(`/api/user/reminder/toggle/${userId}?enabled=${enabled}`, null, { 
      showLoading: true, 
      loadingText: enabled ? '开启提醒中...' : '关闭提醒中...' 
    }),
  
  // 设置提醒间隔
  setReminderInterval: (userId: number, intervalMinutes: number) => 
    http.post(`/api/user/reminder/interval/${userId}?intervalMinutes=${intervalMinutes}`, null, { 
      showLoading: true, 
      loadingText: '设置间隔中...' 
    }),
  
  // 获取提醒统计信息
  getReminderStats: (userId: number) => 
    http.get(`/api/user/reminder/stats/${userId}`),

  // ==================== 微信公众号相关接口 ====================
  
  // 绑定微信公众号openid
  bindWechatOpenid: (data: { userId: number; scene?: number; referrerAppId?: string; authCode?: string }) => 
    http.post('/api/wechat/bind-openid', data, { 
      showLoading: true, 
      loadingText: '绑定微信中...' 
    }),
  
  // 检查公众号openid绑定状态
  checkWechatBinding: (userId: number) => 
    http.get(`/api/wechat/binding/${userId}`),
  
  // 发送测试模板消息
  sendTestTemplateMessage: (userId: number) => 
    http.post(`/api/wechat/template/send/test`, { userId }, { 
      showLoading: true, 
      loadingText: '发送测试消息中...' 
    }),
  
  // 获取公众号授权URL
  getOfficialAccountAuthUrl: (state?: string, redirectUri?: string) => {
    let url = '/api/wechat/official/auth-url';
    const params = [];
    
    if (redirectUri) {
      params.push(`redirectUri=${encodeURIComponent(redirectUri)}`);
    }
    if (state) {
      params.push(`state=${encodeURIComponent(state)}`);
    }
    
    if (params.length > 0) {
      url += '?' + params.join('&');
    }
    
    return http.get(url, null, { skipAuth: true });
  },
  
  // 公众号授权回调处理
  handleOfficialAccountCallback: (code: string, state?: string) => 
    http.get(`/api/wechat/official/callback?code=${code}&state=${encodeURIComponent(state || '')}`),
  
  // 绑定公众号到用户
  bindOfficialAccount: (officialAccountOpenid: string) =>
    http.post('/api/wechat/bind/official-account', { officialAccountOpenid })
};

export default api;
export { http, authManager };
